package http.dtail;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerV3 {
    static class User{
        public String name;
        public String password;
        public String school;
    }

    private ServerSocket serverSocket = null;
    private Map<String,User> sessions = new HashMap<>();
    public HttpServerV3(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动 ");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    process(clientSocket);
                }
            });
        }
    }

    private void process(Socket clientSocket) {
        // 处理核心 逻辑
        try{
            // 1.读取请求 并 解析
            HttpRequest request = HttpRequest.build(clientSocket.getInputStream());
            HttpResponse response = HttpResponse.build(clientSocket.getOutputStream());
            // 2. 根据请求 计算响应
            response.setStatus(200);
            response.setMessage("OK");
            if("GET".equalsIgnoreCase(request.getMethod())){
                doGet(request,response);
            }else if("POST".equalsIgnoreCase(request.getMethod())){
                doPost(request,response);
            }else {
                response.setStatus(405);
                response.setMessage("Method Not Allowed");
            }
            // 3 . 把响应写回到客户端
            response.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doPost(HttpRequest request, HttpResponse response) throws IOException {
         // 2. 实现一个 /login 的处理
        String uid1 = request.getCookies("uid");
        // 这个只支持 一个uid cookie 的设置 不支持多个 所以不行(一台电脑只允许个账户登录)
        if (uid1 == null) {
            if(request.getUrl().startsWith("/login")){
                String username = request.getParameters("username");
                String password = request.getParameters("password");
    //            // TODO 这里 只是打印出来需要后面 做项目的时候就得是 数据库的交互了
    //            System.out.println("username =" + username );
    //            System.out.println("password =" + password);
                User user = new User();
                user.name = username;
                user.password = password;
                user.school = "西安工程大学";
                // 通过 session 来持久化登录 防止 因为 cookie 太过单纯 导致信息泄露
                String uid = UUID.randomUUID().toString();
                response.setHeaders("Set-Cookie","uid="+uid);
                sessions.put(uid,user);
                response.writeBody("<html>\n");
                response.writeBody("<head>\n");
                response.writeBody("<meta charset=\"utf-8\">\n");
                response.writeBody("</head>\n");
                response.writeBody("<h1>"+user.name+ " 登录 成功"+"</h1>\n");
                response.writeBody("</html>\n");
            }
        }else {
            User user = sessions.get(uid1);
            response.writeBody("<html>\n");
            response.writeBody("<head>\n");
            response.writeBody("<meta charset=\"utf-8\">\n");
            response.writeBody("</head>\n");
            response.writeBody("<h1>"+user.name+ "已经登录 不用再次登录"+"</h1>\n");
            response.writeBody("</html>\n");
        }
    }

    private void doGet(HttpRequest request, HttpResponse response) throws IOException {
        // 1. 能够支持 返回一个 html 文件 ]\
        if(request.getUrl().startsWith("/index.html")){
            // 这种情况就让代码 读取一个 index.html 文件
            // 获取一个类的类对象  获取类加载器   利用类加载器查找资源
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("index.html");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            // 按行读取内容
            String line = null;
            while((line = bufferedReader.readLine()) != null){
                response.writeBody(line+"\n");
            }
            bufferedReader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        HttpServerV3 serverV3 = new HttpServerV3(9090);
        serverV3.start();
    }
}
